import asyncio
import requests
import aiohttp


# 协程实现平均数
def coro_avg():
    total = 0
    lengh = 0
    while True:
        try:
            value = yield total/lengh
        except ZeroDivisionError:
            value = yield 0
        total += value
        lengh += 1

my_avg = coro_avg()
next(my_avg)
print(my_avg.send(1))
print(my_avg.send(2))
print(my_avg.send(3))


# asyncio异步程序
async def do_something(index):
    print(f"第{index}个任务启动")
    await asyncio.sleep(1)
    print(f"第{index}个任务完成")

loop = asyncio.get_event_loop()
task_array = []
for i in range(10):
    task_array.append(do_something(i))
loop.run_until_complete(asyncio.wait(task_array))


# aiohttp异步请求网页
async def fetch(session, url):
    async with session.get(url) as response:
        return await response.text()

async def bilibili_request(index):
    print(f"第{index}个网页抓取启动")
    async with aiohttp.ClientSession() as session:
        html = await fetch(session, "https://www.bilibili.com/")
        print(html)
task_array2 = []
for i in range(10):
    task_array2.append(bilibili_request(i))
loop.run_until_complete(asyncio.wait(task_array2))
loop.close()
